package com.ajie.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.ajie.model.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * @author: ajie
 * @createTime: 2024-06-23 11:30
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(value = NotLoginException.class)
    public Result<String> handle(NotLoginException e, HttpServletRequest request) {
        // 如果没有传递token时，应返回未传递登陆凭证
        String tokenName = request.getHeader(StpUtil.getTokenName());
        if (StrUtil.isBlank(tokenName)) {
            return Result.error(401, "未传递登陆凭证", request.getRequestURI());
        }
        log.error("Sa-Token鉴权异常 --- url: {}", request.getRequestURI(), e);
        return Result.error(401, e.getMessage(), request.getRequestURI());
    }

    @ExceptionHandler(value = NotRoleException.class)
    public Result<String> handle(NotRoleException e, HttpServletRequest request) {
        log.error("Sa-Token鉴权异常 --- url: {}", request.getRequestURI(), e);
        return Result.error(403, e.getMessage(), request.getRequestURI());
    }

    @ExceptionHandler(value = NotPermissionException.class)
    public Result<String> handle(NotPermissionException e, HttpServletRequest request) {
        log.error("Sa-Token鉴权异常 --- url: {}", request.getRequestURI(), e);
        return Result.error(403, e.getMessage(), request.getRequestURI());
    }

    @ExceptionHandler(value = SQLException.class)
    public Result<String> handle(SQLException e, HttpServletRequest request) {
        log.error("SQL异常 --- url: {}", request.getRequestURI(), e);
        return Result.error(500, "SQL异常", e.getMessage());
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public Result<String> handle(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.error("请求异常 --- url: {}", request.getRequestURI(), e);
        return Result.error(500, "不被允许的请求", e.getMessage());
    }

}
